import queue
from threading import Thread

flag = 0


# producer 生产者
def read_phone_from_file(path):
    with open(path) as f:
        phone = f.readlines()
        for i in phone:
            email = get_email_by_phone(i[:-1])
            print(f'--------我是生产者，生产了一条数据：{email}')
            q.put(email)
    global flag
    flag = 1
    # 生产者结束
    print("producer end")


# consumer 消费者
def write_email_to_file(path):
    while True:
        if q.empty() and flag == 1:
            print("********我是消费者，队列为空，且生产者已经处理完毕，消费者结束运行")
            break

        if q.empty():
            print("********我是消费者，队列空着呢..没获取到数据。")
            pass
        else:
            email = q.get()
            print(f"********我是消费者，获取一条数据:{email}")
            with open(path, 'w', encoding='utf8') as f:
                f.write(email + '\n')
    # 消费者结束
    print("consumer end")


# 电话转邮件 服务
def get_email_by_phone(phone):
    return f"{phone}@163.com"


if __name__ == '__main__':
    # 生产者向队列中存入数据，消费者从队列中消费数据
    q = queue.Queue()
    print(q.empty())

    p = Thread(target=read_phone_from_file, args=("./phone.txt",))
    p.start()

    c = Thread(target=write_email_to_file, args=("./email.txt",))
    c.start()

    print("主进程")
